'''
Author        zzx
Date          2022-08-05 17:26:24
LastEditTime  2022-09-15 16:23:51
LastEditors   zzx
Description   自定义命令
'''

import click
from sqlalchemy import text
from app.extensions.sqlalchemy import db
from app.modules.v1.permission.models import Role
from app.modules.v1.user.models import User
from app.modules.v1.dict_data.models import Dict
from app.extensions.initialization.fakes import PermissionFake


def configure_cli(app):
    """自定义命令"""

    @app.cli.command('recreate_db', short_help='recreate_db')
    def recreate_db():
        """重新创建数据表."""
        click.echo('Rebuild the database...')
        db.session.execute(text('SET FOREIGN_KEY_CHECKS=0;'))
        db.drop_all()
        db.create_all()
        db.session.execute(text('SET FOREIGN_KEY_CHECKS=1;'))

    @app.cli.command('db_destroy', short_help='db_destroy')
    def db_destroy():
        """删除数据表."""
        click.echo('Destroy the database...')
        db.session.execute(text('SET FOREIGN_KEY_CHECKS=0;'))
        db.drop_all()
        db.session.execute(text('SET FOREIGN_KEY_CHECKS=1;'))

    @app.cli.command('db_migrate', short_help='db_migrate')
    def db_migrate():
        """重新创建数据表."""
        click.echo('migrate the database...')
        db.session.execute(text('SET FOREIGN_KEY_CHECKS=0;'))
        db.session.execute(text('delete from alembic_version;'))
        db.session.commit()
        db.session.execute(text('SET FOREIGN_KEY_CHECKS=1;'))

    @app.cli.command('init_admin', short_help='init_admin')
    def init_admin():
        """初始化管理员"""
        click.echo('Initializing the roles and permissions...')
        Role.init_data()
        click.echo('Initializing the admins...')
        User.init_data()

    @app.cli.command('init_permissions', short_help='init_permissions')
    def init_permissions():
        click.echo('Initializing the roles and permissions...')
        Role.init_data()

    @app.cli.command('init_fake', short_help='init_fake')
    def init_fake():
        """初始化假数据"""
        click.echo('Initializing the fake permission data...')
        PermissionFake.fake_apis(10)

    @app.cli.command('init_data', short_help='init_data')
    def init_data():
        """初始化源数据基本数据"""
        click.echo('Initializing the Dict data...')
        Dict.init_data()
